import path from 'path';

import {expect} from '@jest/globals';

import {runHvigorAsync} from '../../common/common';
import {commonFileOperation} from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from '../../plugins/project-builder/models/constants';
import {TestCaseBuilder} from '../../plugins/task-builder/task-case-builder';
import {ProjectBuildOption, TestCaseFun} from '../../plugins/task-builder/test-case';
import {TestTaskOptionBuilder} from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: [ModuleTemplateType.StaticLibrary]
};

/**
 *  packageHar cache目录通过 hvigor api 拼接得到，确保该拼接方式一直有效
 *
 */
const testFun: TestCaseFun = async (project, _, record) => {
  const libraryPath = project.getModule('staticLibrary').moduleRootPath();

  // 修改 staticLibrary/hvigorfile.ts 文件，加入用户自定插件
  await commonFileOperation(path.resolve(libraryPath, 'hvigorfile.ts'), async () => {
    return `
import { OhosHarContext, OhosPluginId, Target, harTasks } from "@ohos/hvigor-ohos-plugin";
import { FileUtil, hvigor, HvigorNode, HvigorPlugin } from '@ohos/hvigor';

export class MyPlugin implements HvigorPlugin {
    pluginId: string = "Find packageHar cache dir"

    apply(node: HvigorNode) {
        hvigor.nodesEvaluated(() => {
            this.harTask(node);
        })
    }

    harTask(node: HvigorNode) {
        const harContext = node.getContext(OhosPluginId.OHOS_HAR_PLUGIN) as OhosHarContext;
        harContext?.targets((target: Target) => {
            const targetName = target.getTargetName();
            const packageHar = node.getTaskByName(\`\${targetName}@ProcessHarArtifacts\`);
            if (packageHar == null || packageHar == undefined) {
                throw new Error("PackageHar task not found!")
            }
            node.getTaskByName(\`\${targetName}@ProcessHarArtifacts\`)
                .afterRun((taskContext) => {
                    const targetCachePath = FileUtil.pathResolve(
                        target.getBuildTargetOutputPath(),
                        '..', '..', 'cache',
                        targetName,
                        \`\${targetName}@PackageHar\`);
                    if (!FileUtil.exist(targetCachePath)) {
                        throw new Error("PackageHar cache dir not found!");
                    }
                })
        })
    }
}

export default {
    system: harTasks,
    plugins: [new MyPlugin()]
}`;
  });

  const commands: string[] = '--mode module -p product=default -p module=staticLibrary@default assembleHar --no-daemon'.split(' ');
  const result = await runHvigorAsync(project.projectRootPath(), commands);
  record.addStep('编译构建staticLibrary模块', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
};

TestCaseBuilder.builder()
  .caseName('DTS2025032837848')
  .description('通过 hvigor API 获取 packageHar 缓存目录位置')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.DTS).build())
  .testFun(testFun)
  .load();
